﻿using System;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;

namespace yunio._req_http
{
    using rehot;
    using yunio.helpers;
    internal class HttpClient
    {
        static HttpClient()
        {
            using var manager = new HotType(typeof(ServicePointManager));
            if (manager.FindAttribute("Obsolete") == null) //过时不设置
            {
                ServicePointManager.SecurityProtocol = (SecurityProtocolType)(48 | 192 | 768 | 3072);
                using var hot = new HotType(typeof(SecurityProtocolType));
                foreach (var id in hot.Members.AllMemberId())
                    if (hot.Members.ReadNameById(id) != "value__")
                        ServicePointManager.SecurityProtocol |= hot.Members.GetByMemberId<SecurityProtocolType>(null, id);
                ServicePointManager.Expect100Continue = false;
                ServicePointManager.DefaultConnectionLimit = 100;
            }
        }
        public static string GetText(string url)
        {
            string responseText = string.Empty;

            // 创建请求对象
            var request = NormalWeb.Get(url);
            using var response = NormalWeb.GetResponse(request);
            using (var reader = NormalWeb.OpenReader(response))
                responseText = reader.ReadToEnd();

            return responseText;
        }
        public static string PostJson(string url)
        {
            string responseText = string.Empty;

            // 创建请求对象
            var request = NormalWeb.PostJson(url);
            using var response = NormalWeb.GetResponse(request);
            using (var reader = NormalWeb.OpenReader(response))
                responseText = reader.ReadToEnd();
            return responseText;
        }
        public static string PostJson(string url, YunioJson post_data)
        {
            string responseText = string.Empty;

            var request = NormalWeb.PostJson(url);
            NormalWeb.WriteJson(request, post_data);

            using var response = NormalWeb.GetResponse(request);
            using (var reader = NormalWeb.OpenReader(response))
                responseText = reader.ReadToEnd();
            return responseText;
        }
        public static string Post(string url, string post_data)
        {
            string responseText = string.Empty;

            var request = NormalWeb.PostFormData(url);
            NormalWeb.WriteFormData(request, post_data);

            using var response = NormalWeb.GetResponse(request);
            using (var reader = NormalWeb.OpenReader(response))
                responseText = reader.ReadToEnd();
            return responseText;
        }
        public static HttpStatusCode JustPost(string url, string post_data)
        {
            var request = NormalWeb.PostFormData(url);
            NormalWeb.WriteFormData(request, post_data);

            using var response = NormalWeb.GetResponse(request);
            return response.StatusCode;
        }
        public static void DownloadToFile(string url, string path)
        {
            string responseText = string.Empty;
            var request = NormalWeb.Get(url);

            using var response = NormalWeb.GetResponse(request);
            using var file = File.Create(path);
            using var reqstream = NormalWeb.GetStream(response);
            helper.ReadAllToMemory(reqstream, file);
        }
        public static Stream Download(string url, out string filename)
        {
            string responseText = string.Empty;
            var request = NormalWeb.Get(url);

            using var response = NormalWeb.GetResponse(request);
            filename = GetDownloadFileName(response);
            var mem = new MemoryStream();
            using var reqstream = NormalWeb.GetStream(response);
            helper.ReadAllToMemory(reqstream, mem);
            mem.Position = 0;
            return mem;
        }
        public static Stream PostDownload(string url, YunioJson post_data, out string filename)
        {
            string responseText = string.Empty;
            var request = NormalWeb.PostJson(url);
            NormalWeb.WriteJson(request, post_data);

            using var response = NormalWeb.GetResponse(request);
            filename = GetDownloadFileName(response);
            var mem = new MemoryStream();
            using var reqstream = NormalWeb.GetStream(response);
            helper.ReadAllToMemory(reqstream, mem);
            mem.Position = 0;
            return mem;
        }
        public static Stream PostDownload(string url, string post_data, out string filename)
        {
            filename = string.Empty;
            var request = NormalWeb.PostFormData(url);
            NormalWeb.WriteFormData(request, post_data);

            using var response = NormalWeb.GetResponse(request);
            filename = GetDownloadFileName(response);
            var mem = new MemoryStream();
            using var reqstream = NormalWeb.GetStream(response);
            helper.ReadAllToMemory(reqstream, mem);
            mem.Position = 0;
            return mem;
        }
        public static string PostUpload(string url, MultiContent content)
        {
            string responseText = string.Empty;
            var request = NormalWeb.PostFormData(url);
            NormalWeb.WriteMultiContent(request, content);

            using var response = NormalWeb.GetResponse(request);
            using (var reader = NormalWeb.OpenReader(response))
                responseText = reader.ReadToEnd();
            return responseText;
        }
        public static HttpStatusCode JustPostUpload(string url, MultiContent content)
        {
            var request = NormalWeb.PostFormData(url);

            request.KeepAlive = true;
            NormalWeb.WriteMultiContent(request, content);

            using var response = NormalWeb.GetResponse(request);
            return response.StatusCode;
        }
        internal static string GetDownloadFileName(HttpWebResponse response)
        {
            string disposition = response.GetResponseHeader("Content-Disposition");
            if (string.IsNullOrEmpty(disposition)) return Path.GetFileName(response.ResponseUri.AbsolutePath);
            // 解析Content-Disposition头
            return ParseFileName(disposition);
        }
        internal static string ParseFileName(string disposition)
        {
            // 匹配filename参数（支持带引号和编码格式）
            var match = Regex.Match(disposition, @"filename\*?=['""]?([^'""]+)['""]?", RegexOptions.IgnoreCase);
            if (match.Success)
            {
                string fileName = match.Groups[1].Value;

                // 处理RFC 5987编码格式（如filename*=UTF-8''%E6%96%87%E4%BB%B6.txt）
                if (fileName.StartsWith("UTF-8''", StringComparison.OrdinalIgnoreCase))
                    fileName = Uri.UnescapeDataString(fileName.Substring(7));
                else fileName = Uri.UnescapeDataString(fileName);
                return fileName;
            }
            return string.Empty; // 默认文件名
        }
    }
}
